package res

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"zswei.xyz/manager/utils"
)

type Response struct {
	Code int    `json:"code"`
	Data any    `json:"data"`
	Desc string `json:"desc"`
}

type ListResponse[T any] struct {
	Count int64 `json:"count"`
	List  T     `json:"list"`
}

// Result 封装响应体
func Result(code int, data any, docs string, c *gin.Context) {
	c.JSON(http.StatusOK, Response{
		Code: code,
		Data: data,
		Desc: docs,
	})
}

// 定义响应码状态
const (
	Success = 0  // 成功
	Error   = -1 // 失败
)

// Ok 封装成功响应
func Ok(data any, desc string, c *gin.Context) {
	Result(Success, data, desc, c)
}

// OkWithData 成功响应数据
func OkWithData(data any, c *gin.Context) {
	Result(Success, data, "", c)
}

// OkWithList 成功返回分页数据
func OkWithList(list any, count int64, c *gin.Context) {
	OkWithData(ListResponse[any]{
		List:  list,
		Count: count,
	}, c)
}

// OkWithDesc 成功响应描述
func OkWithDesc(desc string, c *gin.Context) {
	Result(Success, "null", desc, c)
}

// OkWith 成功
func OkWith(c *gin.Context) {
	Result(Success, "null", "", c)
}

// Fail 封装失败响应
func Fail(data any, desc string, c *gin.Context) {
	Result(Error, data, desc, c)
}

// FailWithDesc 失败响应描述
func FailWithDesc(desc string, c *gin.Context) {
	Result(Error, "null", desc, c)
}

// FailWithCode 失败响应状态码
func FailWithCode(code ErrorCode, c *gin.Context) {
	desc, ok := ErrorMap[code]
	if ok {
		Result(int(code), "null", desc, c)
		return
	}
	Result(Error, "null", "未知错误", c)
}

// 错误信息ZH展示
func FailWithErrorDesc(err error, obj any, c *gin.Context) {
	msg := utils.GetValidMsg(err, obj)

	FailWithDesc(msg, c)
}
